/*
 * 文 件 名 : AutoUpdate.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-10-24
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Toast;

import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 新版本检测
 * 下载、安装
 *
 * @author  lixg
 * @version [版本号,2012-10-24]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class AutoUpdate
{
    public Activity activity = null;   
    public int versionCode = 0;   
    public String versionName = "";   
    //新版本号
    public int newVerCode;
    //新版本名
    public String newVerName;
    public String newVerContext;//新版本更新的内容
    
    private static final String TAG = "AutoUpdate";   
    private String currentFilePath = "";   
    private String currentTempFilePath = "";   
    private String fileEx = "";   
    private String fileNa = "";   
    private String apkURL = DolphinApplication.URL+"upload/apk/Dolphin.apk";   
    private final String verInfoURL=DolphinApplication.URL+"comm/getVersion.php";
    private ProgressDialog dialog;   
    public AutoUpdate(Activity activity) {   
        this.activity = activity;   
        getCurrentVersion();   
    }   
    public void check() {   
        if (isNetworkAvailable(this.activity) == false) {   
            return;   
        }   
        if (checkNewVerInfo()) {// Check version.   
            showUpdateDialog();   
        }else
        {
            Toast.makeText(activity, "您目前的是最新版本，谢谢您的支持", Toast.LENGTH_LONG).show();
        }
    }   
    public static boolean isNetworkAvailable(Context ctx) {   
        try {   
            ConnectivityManager cm = (ConnectivityManager) ctx   
                    .getSystemService(Context.CONNECTIVITY_SERVICE);   
            NetworkInfo info = cm.getActiveNetworkInfo();   
            return (info != null && info.isConnected());   
        } catch (Exception e) {   
            e.printStackTrace();   
            return false;   
        }   
    }   
    public void showUpdateDialog() {   
        @SuppressWarnings("unused")   
        AlertDialog alert = new AlertDialog.Builder(this.activity)   
                .setTitle("版本更新")   
                .setIcon(R.drawable.icon)   
                .setMessage("检测到有新版本，内容如下：\r\n"+newVerContext+"\r\n是否需要更新？")   
                .setPositiveButton("更新",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                downloadTheFile(apkURL);   
                                showWaitDialog();   
                            }   
                        })   
                .setNegativeButton("关闭",   
                        new DialogInterface.OnClickListener() {   
                            public void onClick(DialogInterface dialog,   
                                    int which) {   
                                dialog.cancel();   
                            }   
                        }).show();   
    }   
    public void showWaitDialog() {   
        dialog = new ProgressDialog(activity);   
        dialog.setMessage("下载中，请稍候...");   
        dialog.setIndeterminate(true);   
        dialog.setCancelable(true);   
        dialog.show();   
    }   
    public void getCurrentVersion() {   
        try {   
            PackageInfo info = activity.getPackageManager().getPackageInfo(   
                    activity.getPackageName(), 0);   
            this.versionCode = info.versionCode;   
            this.versionName = info.versionName;   
        } catch (NameNotFoundException e) {   
            e.printStackTrace();   
        }   
    }   
    //获取服务器上的版本信息
    public boolean checkNewVerInfo()
    {
        boolean flag=false;//是否有新版本
        List<NameValuePair> param = new ArrayList<NameValuePair>();
        param.add(new BasicNameValuePair("versionCode",String.valueOf(versionCode)));
        //param.add(new BasicNameValuePair("versionName",versionName));
        String json = RequestUtils.getInstall().getHttpJson(verInfoURL, param);
        if(json != null)
        {
            try
            {
                JSONObject data = new JSONObject(json);
                String msgCode = data.getString("msgCode");
                if("1".equals(msgCode))
                {
                    JSONObject object = data.getJSONObject("msgBody");
                    newVerCode = object.getInt("verCode");
                    newVerName = object.getString("verName");
                    newVerContext = object.getString("remark");
                    flag=true;
                }else
                {
                    LogUtil.e(data.getString("desc"));
                }
            }
            catch (JSONException e)
            {
                LogUtil.e("", e);
            }
            
        }
        return flag;
    }
    private void downloadTheFile(final String strPath) {   
        fileEx = apkURL.substring(apkURL.lastIndexOf(".") + 1, apkURL.length())   
                .toLowerCase();   
        fileNa = apkURL.substring(apkURL.lastIndexOf("/") + 1,   
                apkURL.lastIndexOf("."));   
        try {   
            if (strPath.equals(currentFilePath)) {   
                doDownloadTheFile(strPath);   
            }   
            currentFilePath = strPath;   
            Runnable r = new Runnable() {   
                public void run() {   
                    try {   
                        doDownloadTheFile(strPath);   
                    } catch (Exception e) {   
                        Log.e(TAG, e.getMessage(), e);   
                    }   
                }   
            };   
            new Thread(r).start();   
        } catch (Exception e) {   
            e.printStackTrace();   
        }   
    }   
    private void doDownloadTheFile(String strPath) throws Exception {   
        Log.i(TAG, "getDataSource()");   
        if (!URLUtil.isNetworkUrl(strPath)) {   
            Log.i(TAG, "getDataSource() It's a wrong URL!");   
        } else {   
            URL myURL = new URL(strPath);   
            URLConnection conn = myURL.openConnection();   
            conn.connect();   
            InputStream is = conn.getInputStream();   
            if (is == null) {   
                throw new RuntimeException("stream is null");   
            }   
            File myTempFile = File.createTempFile(fileNa, "." + fileEx);   
            currentTempFilePath = myTempFile.getAbsolutePath();   
            FileOutputStream fos = new FileOutputStream(myTempFile);   
            byte buf[] = new byte[128];   
            do {   
                int numread = is.read(buf);   
                if (numread <= 0) {   
                    break;   
                }   
                fos.write(buf, 0, numread);   
            } while (true);   
            Log.i(TAG, "getDataSource() Download  ok...");   
            dialog.cancel();   
            dialog.dismiss();   
            openFile(myTempFile);   
            try {   
                is.close();   
            } catch (Exception ex) {   
                Log.e(TAG, "getDataSource() error: " + ex.getMessage(), ex);   
            }   
        }   
    }   
    private void openFile(File f) {   
        Intent intent = new Intent();   
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);   
        intent.setAction(android.content.Intent.ACTION_VIEW);   
        String type = getMIMEType(f);   
        intent.setDataAndType(Uri.fromFile(f), type);   
        activity.startActivity(intent);   
    }   
    public void delFile() {   
        Log.i(TAG, "The TempFile(" + currentTempFilePath + ") was deleted.");   
        File myFile = new File(currentTempFilePath);   
        if (myFile.exists()) {   
            myFile.delete();   
        }   
    }   
    private String getMIMEType(File f) {   
        String type = "";   
        String fName = f.getName();   
        String end = fName   
                .substring(fName.lastIndexOf(".") + 1, fName.length())   
                .toLowerCase();   
        if (end.equals("m4a") || end.equals("mp3") || end.equals("mid")   
                || end.equals("xmf") || end.equals("ogg") || end.equals("wav")) {   
            type = "audio";   
        } else if (end.equals("3gp") || end.equals("mp4")) {   
            type = "video";   
        } else if (end.equals("jpg") || end.equals("gif") || end.equals("png")   
                || end.equals("jpeg") || end.equals("bmp")) {   
            type = "image";   
        } else if (end.equals("apk")) {   
            type = "application/vnd.android.package-archive";   
        } else {   
            type = "*";   
        }   
        if (end.equals("apk")) {   
        } else {   
            type += "/*";   
        }   
        return type;   
    }   
}
